import {getMenuList} from '@/api/role.js'

const getMenus = () => {
  var menuList = [{
    icon: 'el-icon-setting',
    text: '用户管理',
    index: '/system',
    children: [
      {
        icon: 'el-icon-user',
        text: '角色管理',
        index: '/system/role/role'
      },
      {
        icon: 'el-icon-files',
        text: '账号管理',
        index: '/system/role/accountNumber'
      }
    ]
  }];
  return menuList;
}

const state = {
  menus: []
}

const mutations = {
  RESET_STATE: (state) => {
    state.menus = []
  },
  CHANGE_STATE: (state, {key, value}) => {
    if (state.hasOwnProperty(key)) {
      state[key] = value
    }
  }

}

const actions = {
  // 加载角色菜单
  async loadMenuList({ commit }) {
    const res = await getMenuList();
    var menus = res.data;
    formatMenus(menus)
    // console.log(menus)
    commit('RESET_STATE');
    commit('CHANGE_STATE', {key: 'menus', value: menus})
  }

}

/**
 * 格式化菜单
 * @param {Object} menus
 */
function formatMenus(menus) {
  // 只保留需要字段
  for(var i = 0; i < menus.length; i++) {
      var {icon, index, text, children} = menus[i];
      if(children && children.length > 0) {
         formatMenus(children);
      }
      menus[i] = {
        icon, index, text, children
      }
  }

}


export default {
  namespaced: true,
  state,
  mutations,
  actions
}
